//
//  IOPack.h
//  RunSketch
//
//  Created by Brian on 9/3/09.
//  Copyright 2009 Tellart. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "IOPackTransport.h"
#import "SketchProtocol.h"


#define IOPACK_INPUT_VALUE unsigned char
#define IOPACK_OUTPUT_VALUE unsigned char

#define kFlowControlWaitForSetTimeout 1.0f

@interface IOPack : NSObject {
    id <IOPackTransport> transport;

    NSMutableData *lastOutputValues;
    NSMutableData *outputValues;
    
    NSMutableData *lastInputValues;
    NSMutableData *inputValues;
    
    BOOL flowControl;
    CFAbsoluteTime now;
    CFAbsoluteTime serverFlowControlWaitForSetUntil;
    
    /** parsing stuff **/
    BOOL waitingForSet;
    char cin;
    NSRange setValuesRange;
    int readBufferCursor;
    int numLastBytesRead;
    int incomingMessageBufferCursor;
    int incomingMessageBufferExpectedLength;
    unsigned int incomingMessageBufferSize;
    char *incomingMessageBuffer;
    char *outgoingMessageBuffer;
    unsigned int outgoingMessageBufferSize;
    
    //instrumentation
    CFAbsoluteTime  lastIOPackSampleTime;
    float actualIOPackSamplingRate;

}

/* private methods */
- (void) allocBuffers;
- (void) deallocBuffers;
- (void) allocValues;
- (void) deallocValues;
- (void) sendGetMessage;
- (void) sendSetMessage;
- (void) processInputBuffer;
- (void) parseMessageFromBuffer;

/* public properties */
@property (nonatomic, retain) NSMutableData *inputValues;
@property (nonatomic, retain) NSMutableData *outputValues;


/* public methods */
-(BOOL)isReady;
- (NSString *)deviceAddress;
- (int)numOutputChannels;
- (int)numInputChannels;
-(id)initWithTransport:(id <IOPackTransport>)pTransport;
-(void)setOutputValues:(NSMutableData*)values;
-(void)setHardwareOutputsFromOutputValues;
-(BOOL)setInputValuesFromHardwareInputs;
-(void)setFlowControl:(BOOL)state;
-(BOOL)getFlowControl;

@end

